package com.captain.leetcode.动态规划;

import java.util.Random;

/**
 * Des:
 *
 * @author XL
 * @Date 2022/1/5 14:17
 */
public class 买卖股票的最佳时机121 {

    public static void main(String[] args) {
        System.out.println(new 买卖股票的最佳时机121().maxProfit4(new int[]{7, 1, 5, 3, 6, 4}));
    }

    public int maxProfit(int[] prices) {
        int res = 0;
        for (int i = 0; i < prices.length; i++) {
            for (int j = i + 1; j < prices.length; j++) {
                res = Math.max(prices[j] - prices[i], j);
            }
        }
        return res;
    }

    public int maxProfit1(int[] prices) {
        //贪心算法 ,取左边的最小值 , 右边的最大值
        int low = Integer.MAX_VALUE;
        int res = 0;
        for (int price : prices) {
            low = Math.min(low, price);
            res = Math.max(price - low, res);
        }
        return res;
    }

    public int maxProfit2(int[] prices) {
        //贪心算法 ,取左边的最小值 , 右边的最大值
        int low = Integer.MAX_VALUE;
        int res = 0;
        for (int price : prices) {
            low = Math.min(low, price);
            res = Math.max(price - low, res);
        }
        return res;
    }

    public int maxProfit3(int[] prices) {
        int len = prices.length;
        if (len == 0) return 0;
        //dp[i][0] : 持有股票
        //dp[i][1] : 未持有股票
        int[][] dp = new int[len + 1][2];
        dp[0][0] = -prices[0];
        dp[0][1] = 0;
        for (int i = 1; i < prices.length; i++) {
            dp[i][0] = Math.max(dp[i - 1][0], -prices[i]);
            dp[i][1] = Math.max(dp[i - 1][1], dp[i - 1][0] + prices[i]);
        }
        return dp[len - 1][1];
    }

    public int maxProfit4(int[] prices) {
        int len = prices.length;
        if (len == 0) return 0;
        //dp[i][0] : 持有股票
        //dp[i][1] : 未持有股票
        int[][] dp = new int[len + 1][2];
        dp[0][0] = -prices[0];
        dp[0][1] = 0;
        for (int i = 1; i < prices.length; i++) {
            //前一天持有股票 或者 前一天没有持有股票 + 今天买入股票
            dp[i][0] = Math.max(dp[i - 1][0], dp[i][1] - prices[i]);
            dp[i][1] = Math.max(dp[i - 1][1], dp[i - 1][0] + prices[i]);
        }
        return dp[len - 1][1];
    }
}
